package com.iflytek.tts.TtsService;

//import com.astrob.util.SaveToWave;

import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioTrack;
import android.util.Log;

public class AudioData {
	public static final int mAudioLifecycleType = 1; //1: 播放前分配播放后释放   0：软件启动时分配退出时释放
	private static AudioTrack mAudio = null;
	private static final String TAG = "TtsService(audio)";
	public static int mStreamType = AudioManager.STREAM_MUSIC;
	private static int mSampleRate = 16000;
	private static int mBuffSize = 8000;
	
	public static int AudioStreamType() {
		return mStreamType;
	}

	static {
		initAudioTrack();		
	}
	
//    * @see #STATE_INITIALIZED
//    * @see #STATE_NO_STATIC_DATA
//    * @see #STATE_UNINITIALIZED
	public static int getState() {
		if (null == mAudio) {
			return AudioTrack.STATE_UNINITIALIZED;
		}
		return mAudio.getState();
	}
	
	public static void initAudioTrack()
	{
		if (null == mAudio) {
			mAudio = new AudioTrack(mStreamType, mSampleRate,
					AudioFormat.CHANNEL_CONFIGURATION_MONO,
					AudioFormat.ENCODING_PCM_16BIT, mBuffSize,
					AudioTrack.MODE_STREAM);
		}		
	}
	
	public static void releaseAudioTrack() {
		if (null != mAudio) {
			mAudio.release();
			mAudio = null;
		}
	}
	
	public static void stopAudioTrack() {
		if (null != mAudio) {
			mAudio.stop();
		}
	}
	
	public static void palyAudioTrack() {
		if (null != mAudio) {
			mAudio.play();		
		}
	}
	

	/**
	 * For C call
	 */
	public static void onJniOutData(int len, byte[] data) {

		if (null == mAudio) {
			return;
		}
		if (mAudio.getState() != AudioTrack.STATE_INITIALIZED) {
			return;
		}

		try {
			mAudio.write(data, 0, len);
//			SaveToWave.getInstance().writeTTSDataToFile(data);
			mAudio.play();
		} catch (Exception e) {
			Log.e(TAG, e.toString());
		}
	}

	/**
	 * For C Watch Call back
	 * 
	 * @param nProcBegin
	 */
	public static void onJniWatchCB(int nProcBegin) {
	}

}
